﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CanvasPosChange : MonoBehaviour
{

    private static CanvasPosChange _instance;
    public static CanvasPosChange Instance
    {
        get
        {
            return _instance;
        }
    }
    private CanvasPosChange()
    {
        _instance = this;
    }

    public RectTransform rectCanvas; //画布节点
    public Camera worldCamera; //场景相机

    public void ChangePos(GameObject WordPos, GameObject CanvasPos)
    {
        Vector2 canvasSize = rectCanvas.sizeDelta;
        Vector3 viewPortPos3d = worldCamera.WorldToViewportPoint(WordPos.transform.position);
        Vector2 viewPortRelative = new Vector2(viewPortPos3d.x - 0.5f, viewPortPos3d.y - 0.5f);
        Vector2 cubeScreenPos = new Vector2(viewPortRelative.x * canvasSize.x, viewPortRelative.y * canvasSize.y);

        CanvasPos.GetComponent<RectTransform>().anchoredPosition = cubeScreenPos;
    }

    public void ChangePosition(Vector3 worldPos,GameObject CanvasPos)
    {
        Vector2 canvasSize = rectCanvas.sizeDelta;
        Vector2 viewPortRelative = worldCamera.WorldToViewportPoint(worldPos);
        Vector2 cubeScreenPos = new Vector2(viewPortRelative.x * canvasSize.x, viewPortRelative.y * canvasSize.y);

        CanvasPos.GetComponent<RectTransform>().anchoredPosition = cubeScreenPos;
    }
}
